package com.oneinlet.client.handler

import com.oneinlet.Constant
import com.oneinlet.Pandora
import com.oneinlet.client.ClientChannelManage
import io.netty.buffer.ByteBuf
import io.netty.buffer.ByteBufUtil
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.SimpleChannelInboundHandler
import org.slf4j.LoggerFactory

/**
 * Created by WangZiHe on 2019/1/7/007
 * QQ/WeChat:648830605
 * QQ-Group:368512253
 * Blog:www.520code.net
 * Github:https://github.com/yancheng199287
 */

class ClientProxyHandler : SimpleChannelInboundHandler<ByteBuf>() {


    override fun channelActive(ctx: ChannelHandlerContext?) {

    }

    override fun channelRead0(ctx: ChannelHandlerContext, msg: ByteBuf) {
        val channelId = ClientChannelManage.getClientProxyChannel(ctx.channel().id().asLongText())!!.attr(Constant.channelIdAttributeKey).get()
        val pandora = Pandora()
        pandora.msgType = Pandora.MsgType.SEND_MSG_FROM_YCLINET_TO_YCSERVER.type
        pandora.data = ByteBufUtil.getBytes(msg)
        pandora.channelId = channelId
        pandora.content = "成功获取到本地服务端的消息"
        ClientChannelManage.YCServerChannel.writeAndFlush(pandora)
    }

    override fun channelInactive(ctx: ChannelHandlerContext) {
        val channel = ctx.channel()
        //清除已经断开的通道
        ClientChannelManage.removeClientProxyChannel(channel.id().asLongText())

        //清除缓存的连接通道
        if (channel.hasAttr(Constant.channelIdAttributeKey)) {
            ClientChannelManage.removeClientProxyChannel(channel.attr(Constant.channelIdAttributeKey).get())
        }
        ClientChannelManage.removeClientProxyChannel(ctx.channel().id().asLongText())
    }


    override fun exceptionCaught(ctx: ChannelHandlerContext?, cause: Throwable?) {

    }
}
